package com.hospital.hms.controller;
import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.annotation.SaMode;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.hospital.hms.common.CommonResult;
import com.hospital.hms.controller.form.*;
import com.hospital.hms.pojo.User;
import com.hospital.hms.service.UserService;
import com.hospital.hms.utils.PageUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import javax.validation.Valid;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://localhost:4000", allowCredentials = "true")
@Tag(name = "UserController", description = "用户管理接口")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public CommonResult userLogin(@Valid @RequestBody LoginForm loginForm) {
        HashMap hashMap = JSONUtil.parse(loginForm).toBean(HashMap.class);
        Integer user_id = userService.userLogin(hashMap);
        CommonResult result = CommonResult.ok().put("result", (user_id != null) ? "登录成功" : "登录失败");
        if (user_id != null) {
            /*
            *   Sa-Token框架要求我们用户登陆成功之后，必须在Web方法中执行StpUtil.setLoginId(userId) 生成Token信息
            *   会被保存到redis数据库
            * */
            StpUtil.login(user_id);
            //获取tokenValue和Name，会被保存到redis数据库
            System.out.println(StpUtil.getTokenValue());
            System.out.println(StpUtil.getTokenName());
            //查询用户对应的权限信息集合
            Set<String> privileges = userService.selectUserPrivileges(user_id);
            //将用户权限和token写回到客户端
            result.put("permissions",privileges);
            result.put("token",StpUtil.getTokenValue());
        }
        return result;
    }

    @GetMapping("/logout")
    @SaCheckLogin
    @Operation(summary = "退出登录")
    public CommonResult logout() {
        //删除Token信息
        StpUtil.logout();
        return CommonResult.ok();
    }


    @PostMapping("/selectUserByCondition")
    @Operation(summary = "按条件查询用户带分页")
    @SaCheckPermission(value = {"ROOT", "USER:SELECT"}, mode = SaMode.OR)
    public CommonResult selectUserByCondition(@RequestBody SelectUserConditionByPageForm form) {
        int page = form.getPage();
        int length = form.getLength();
        int start = (page-1) * length;
        HashMap params = JSONUtil.parse(form).toBean(HashMap.class);
        params.put("start",start);
        PageUtils pageUtils = userService.selectUserByCondition(params);
        return CommonResult.ok().put("page",pageUtils);
    }


    @PostMapping("/insert")
    @SaCheckPermission(value = {"ROOT", "USER:INSERT"}, mode = SaMode.OR)
    @Operation(summary = "添加用户")
    public CommonResult insert(@Valid @RequestBody InsertUserForm form) {
        User user = JSONUtil.parse(form).toBean(User.class);
        user.setStatus((byte)1);
        user.setRole(JSONUtil.parseArray(form.getRole()).toString());
        user.setCreateTime(new Date());
        int rows = userService.insert(user);
        return CommonResult.ok().put("rows",rows);
    }

    @PostMapping("/update")
    @SaCheckPermission(value = {"ROOT", "USER:UPDATE"}, mode = SaMode.OR)
    @Operation(summary = "修改用户")
    public CommonResult update(@Valid @RequestBody UpdateUserForm form){
        HashMap param = JSONUtil.parse(form).toBean(HashMap.class);
        //将JSONArray转换为字符串
        param.replace("role",JSONUtil.parseArray(form.getRole()).toString());
        int rows = userService.update(param);
        if(rows == 1) {
            //修改资料后，把用户踢下线
            System.out.println(form.getUserId());
            StpUtil.logoutByLoginId(form.getUserId());
        }
        return CommonResult.ok().put("status",rows);
    }

    @PostMapping("/deleteUserByIds")
    @SaCheckPermission(value = {"ROOT", "USER:DELETE"}, mode = SaMode.OR)
    @Operation(summary = "删除用户")
    public CommonResult deleteUserByIds(@Valid @RequestBody DeleteUserByIdsForm form) {
        //获取到当前用户的ID
        Integer userId = StpUtil.getLoginIdAsInt();
        if(ArrayUtil.contains(form.getIds(),userId)){
            return CommonResult.error("无法删除自己的帐户");
        }

        int rows = userService.deleteUserByIds(form.getIds());
        if(rows > 0) {
            for (Integer id:form.getIds()) {
                //将删除的用户剔下线
                StpUtil.logoutByLoginId(id);
            }
        }
        return CommonResult.ok().put("rows",rows);
    }

    @PostMapping("/selectById")
    @Operation(summary = "根据ID查找用户")
    @SaCheckPermission(value = {"ROOT", "USER:SELECT"}, mode = SaMode.OR)
    public CommonResult selectById(@Valid @RequestBody SelectUserByIdForm form) {
        HashMap map = userService.selectById(form.getUserId());
        return CommonResult.ok(map);
    }


    @GetMapping("/selectAllUser")
    @Operation(summary = "查询所有用户")
    @SaCheckLogin
    public CommonResult searchAllUser() {
        ArrayList<HashMap> list = userService.selectAllUser();
        return CommonResult.ok().put("list", list);
    }

//    @PostMapping("/searchNameAndDept")
//    @Operation(summary = "查找员工姓名和部门")
//    @SaCheckLogin
//    public CommonResult searchNameAndDept(@Valid @RequestBody SearchNameAndDeptForm form){
//        HashMap map=userService.searchNameAndDept(form.getId());
//        return CommonResult.ok(map);
//    }


}